#!/bin/bash
# Copyright 2019 Noah Meyerhans <noahm@debian.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

template="/etc/network/cloud-interfaces-template"
cfgdir="/run/network/interfaces.d"
mkdir -p "$cfgdir"

log() {
    logger --tag "cloud-ifupdown-helper" --priority daemon.debug "$@"
}

do_setup() {
    local working="$cfgdir/.$INTERFACE"
    local final="$cfgdir/$INTERFACE"

    if ifup --no-act "$INTERFACE" > /dev/null 2>&1; then
        # interface is already known to ifupdown, no need to generate cfg
        log "Skipping configuration generation for $INTERFACE"
        return 0
    fi

    sed "s/\\\$INTERFACE/$INTERFACE/g" "$template" > "$working"
    mv "$working" "$final"
    log "Generated configuration for $INTERFACE"

    # Raise the interface here, because we can't rely on the RUN
    # entries from /lib/udev/rules.d/80-ifupdown.rules running after
    # this script:
    systemctl --no-block start $(systemd-escape --template ifup@.service $INTERFACE)
}

if [ -z "$INTERFACE" ]; then
    log 'Bad ifupdown udev helper invocation: $INTERFACE is not set'
    exit 1
fi

do_setup

exit 0

# Local variables:
# mode: shell-script
# tab-width: 4
# indent-tabs-mode: nil
# end:
